<!--
 * @Description: 
 * @Author: 赵大壮
 * @Date: 2021-12-08 14:10:35
 * @LastEditTime: 2022-05-23 18:15:11
 * @LastEditors: 赵大壮
-->
<template>
  <div class="w-full h-full border flex flex-row items-center justify-center">
    <div
      class="p-w10 flex flex-row items-center cursor-pointer"
      v-if="!path"
      @click="selectImg"
    >
      <i class="el-icon-upload2"></i>
      <div class="text-f12">上传文件</div>
      <input
        type="file"
        v-show="false"
        ref="fileRef"
        accept="image/*"
        @change="selecte_img"
      />
    </div>
    <el-image :src="path" fit="fill" class="w-full h-full" v-else />
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";

@Component
export default class UiUploadImg extends Vue {
  @Prop() type: any;
  @Prop() url: any;
  name = "";
  base64 = "";
  path = "";

  created() {}

  mounted() {
    if(this.url){
      this.path = this.url;
    }
  }

  beforeDestroy() {}

  selectImg() {
    (this.$refs.fileRef as any).dispatchEvent(new MouseEvent("click"));
  }

  @Watch("url")
  watchValue(url: any, oldValue: string) {
    console.log("url", url);
    if (url != "") {
      this.path = url;
    }
  }

  // changeUrl(url){
  //   console.log("url",url)
  //   this.path = url;
  // }

  /**
   * 选择图片返回
   */
  selecte_img(image: any) {
    var file = image.path[0].files[0];
    var that = this;
    var oFReader = new FileReader();
    oFReader.readAsDataURL(file);
    oFReader.onloadend = function (oFRevent) {
      var src = oFRevent.target!.result;
      that.path = src as string;
      that.base64 = oFReader.result as string;
      that.name = file.name as string;
      var imageData = {
        name: that.name,
        path: that.path,
        base64: that.base64,
        type: that.type,
      };
      that.$emit("selecte_img", imageData);
    };
  }

  /**
   * 初始化控件
   */
  initView() {
    this.name = "";
    this.base64 = "";
    this.path = "";
    this.$emit("selecte_img", {
      name: this.name,
      path: this.path,
      base64: this.base64,
      type: this.type,
    });
  }
}
</script>
<style lang="less" scoped>
</style>
